package com.jianying.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * ClassName: ${NAME}
 * Package: com.atguigu
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/3/29 11:16
 * @Version: 1.0
 */
public class Flink01_WC_Batch_Bound {
    public static void main(String[] args) throws Exception {
        // TODO 1 指定批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        // TODO 2 从指定文件读取数据
        DataSource<String> dataSource = env.readTextFile("C:\\MyFiles\\Project\\bigdata_flink\\input\\word.txt");
        // TODO 3 对当前数据进行扁平化处理
        FlatMapOperator<String, Tuple2<String, Long>> flatMapDS = dataSource.flatMap(
                new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Long>> collector) throws Exception {
                        String[] words = lineStr.split(" ");
                        for (String word : words) {
                            collector.collect(Tuple2.of(word, 1L));
                        }
                    }
                }
        );
        // TODO 4 按照单词分组
        UnsortedGrouping<Tuple2<String, Long>> groupByDS = flatMapDS.groupBy(0);
        // TODO 5 单词次数求和
        AggregateOperator<Tuple2<String, Long>> sumDS = groupByDS.sum(1);
        // TODO 6 打印输出结果
        sumDS.print();
    }
}